Iterate over a dictionary
A dictionary is a built-in data type that stores data in key-value pairs. Here are some ways to iterate over a dictionary:
1. Iterating over keys
By default, when you loop over a dictionary, you will loop over its keys.
Looping dictionary using keys in python
# Create a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
print(f"Original Dictionary: {my_dict}")
# Loop over the keys
for key in my_dict:
print(key)
Output
Original Dictionary: {'apple': 1, 'banana': 2, 'cherry': 3}
apple
banana
cherry
2. Iterating over values
If you want to loop over the values of a dictionary, you can use the values() method.
Iterate dictionary using value in python
# Create a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
print(f"Original Dictionary: {my_dict}")
# Loop over the values
for value in my_dict.values():
print(value)
Output
Original Dictionary: {'apple': 1, 'banana': 2, 'cherry': 3}
1
2
3
3. Iterating over items
If you want to loop over the key-value pairs of a dictionary, you can use the items() method. This method returns a list of tuples, where each tuple contains a key and a value.
Loop dictionary items in python example
# Create a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
print(f"Original Dictionary: {my_dict}")
# Loop over the items
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
Output
Original Dictionary: {'apple': 1, 'banana': 2, 'cherry': 3}
Key: apple, Value: 1
Key: banana, Value: 2
Key: cherry, Value: 3
4. Dictionary comprehension
This is a concise way to create a new dictionary by iterating over an existing one and applying a condition.
Advanced method to loop over dictionary in python
# Create a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
print(f"Original Dictionary: {my_dict}")
# Create a new dictionary with only the pairs where the value is greater than 1
new_dict = {k: v for k, v in my_dict.items() if v > 1}
print(f"New Dictionary: {new_dict}")
Output
Original Dictionary: {'apple': 1, 'banana': 2, 'cherry': 3}
New Dictionary: {'banana': 2, 'cherry': 3}
Remember, dictionaries in Python are unordered collections of key-value pairs. The order of the elements is not guaranteed to be preserved.